import { IColor } from "./models";

const Gete = (elementId: string) => {
  const dom: HTMLElement = document.getElementById.call(document, elementId);
  return dom;
};

const Newe = ({ type = "div", textContent = "", para = {}}) => {
  const dom = document.createElement(type);
  if (textContent !== "") dom.textContent = textContent;
  // 可能有更好的写法，欢迎迭代。
  for (const key in para) dom[key] = para[key];
  return dom;
};

const CopyTextToClipboard = (text: string) => {
  let isOk = true;
  try {
    navigator.clipboard.writeText(text).then();
  } catch (err) {
    isOk = false;
  }
  return isOk;
};

const RGBToColor = (rgb = "000000") => {
  const rr = rgb[0] + rgb[1];
  const gg = rgb[2] + rgb[3];
  const bb = rgb[4] + rgb[5];
  const r = parseInt(rr, 16);
  const g = parseInt(gg, 16);
  const b = parseInt(bb, 16);
  const color: IColor = { r, g, b, a: 0xff };
  return color;
};

const ColorToRGB = (color: IColor) => {
  const { r, g, b } = color;
  let rr = r.toString(16), gg = g.toString(16), bb = b.toString(16);
  if (r <= 0xf) rr = "0" + rr;
  if (g <= 0xf) gg = "0" + gg;
  if (b <= 0xf) bb = "0" + bb;
  return rr + gg + bb;
};
  
export {
  Gete, Newe,
  CopyTextToClipboard,
  RGBToColor, ColorToRGB,
};
